package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserFocus;
import com.tanhua.model.vo.Counts;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/8 0008 上午 9:53
 */
@DubboService
public class UserFocusApiImpl implements UserFocusApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(UserFocus userFocus) {
        mongoTemplate.save(userFocus);
    }

    @Override
    public void remove(Long userId, String uid) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("userFocusId").is(Long.valueOf(uid)));

        mongoTemplate.remove(query,UserFocus.class);
    }

    @Override
    public Boolean find(Long userId, String uid) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("userFocusId").is(Long.valueOf(uid)));
        List<UserFocus> userFoci = mongoTemplate.find(query, UserFocus.class);
        if(userFoci.size() == 0){
            return false;
        }
        return true;
    }

    @Override
    public Counts countsByUserId(Long userId) {
        //获取当前用户 喜欢的用户及数量
        Query love = Query.query(Criteria.where("userId").is(userId));
        List<UserFocus> loves = mongoTemplate.find(love, UserFocus.class);
        String loveCounts = String.valueOf(mongoTemplate.count(love, UserFocus.class));

        //获取喜欢当前用户 的用户
        Query fen = Query.query(Criteria.where("userFocusId").is(userId));
        List<UserFocus> fans = mongoTemplate.find(fen, UserFocus.class);
        String fenCounts = String.valueOf(mongoTemplate.count(fen, UserFocus.class));

        //获取互相喜欢
        List<Long> loveIds = loves.stream().map(userFocus -> userFocus.getUserFocusId()).collect(Collectors.toList());
        Map<Long, UserFocus> map = fans.stream().collect(Collectors.toMap(
                UserFocus::getUserId,
                userFocus -> userFocus
        ));

        Integer eachLoveCounts = 0;
        for (Long loveId : loveIds) {
            UserFocus userFocus = map.get(loveId);
            if (userFocus.getUserFocusId() == userId){
                eachLoveCounts++;
            }
        }

        return new Counts(eachLoveCounts, Integer.valueOf(loveCounts), Integer.valueOf(fenCounts));
    }
}
